package com.dashan.servlets;

import static com.dashan.Constants.SUCCESS;
import static com.dashan.Constants.USERNAME;
import static com.dashan.Constants.USER_PROFILE;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashan.backend.datastore.DsUserProfile;
import com.dashan.backend.datastore.UserDao;
import com.dashan.backend.util.XmlHelper;
import com.dashan.servlets.Parameter.Option;

@SuppressWarnings("serial")
public class UpdateUserProfileServlet extends DashanPrivateServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(USER_PROFILE, Option.Required, String.class, 
                "user profile in xml format"));
        return res;
    }
    
    @Override
    public String getUrlPattern() {
        return "/updateuserprofile";
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        
        UserDao dao = new UserDao();
        try {
            DsUserProfile profile = 
                dao.getUser(params.get(USERNAME).stringValue()).getProfile();
            
            String xmlString = params.get(USER_PROFILE).stringValue();
            profile.fromXmlElement(XmlHelper.string2Xml(xmlString).getDocumentElement());
            resp.getWriter().print(SUCCESS);
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException(e.getMessage());
        } finally {
            dao.commit();
        }
    }
}
